package com.lucky.back.service.impl;

import com.lucky.back.controller.UploadController;
import com.lucky.back.ex.ServiceException;
import com.lucky.back.mapper.BannerMapper;
import com.lucky.back.pojo.dto.BannerAddNewDTO;
import com.lucky.back.pojo.entity.Banner;
import com.lucky.back.pojo.vo.BannerListItemVO;
import com.lucky.back.pojo.vo.BannerStandardVO;
import com.lucky.back.service.IBannerService;
import com.lucky.back.web.ServiceCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class BannerServiceImpl implements IBannerService {
    @Autowired
    BannerMapper bannerMapper;

    @Autowired
    UploadController uploadController;

    @Override
    public void addNew(BannerAddNewDTO bannerAddNewDTO){
        log.debug("开始处理【添加轮播图】的请求，参数={}",bannerAddNewDTO);
        String url = bannerAddNewDTO.getUrl();
        int count = bannerMapper.countByUrl(url);
        if(count!=0){
            String message = "尝试添加的轮播图已存在！";
            throw new ServiceException(ServiceCode.ERR_INSERT,message);
        }
        Banner banner = new Banner();
        BeanUtils.copyProperties(bannerAddNewDTO,banner);
        log.debug("!!!!!!!!!"+banner.getUrl());
        bannerMapper.insert(banner);
    }

    @Override
    public void delete(Long id){
        log.debug("开始处理【删除轮播图】的请求，参数={}",id);
        BannerStandardVO bannerStandardVO = bannerMapper.getStandardById(id);
        if(bannerStandardVO==null){
            String message = "尝试删除的轮播图不存在！";
            throw new ServiceException(ServiceCode.ERR_INSERT,message);
        }
        log.debug("开始删除相册");
        try {
            uploadController.bannerRemove(bannerStandardVO.getUrl());
        } catch (IOException e) {
            e.printStackTrace();
        }
        bannerMapper.delete(id);
    }

    @Override
    public List<BannerListItemVO> list(){
        log.debug("开始处理【查询轮播图列表】的业务");
        List<BannerListItemVO> list = new ArrayList<>();
        for (BannerListItemVO banner: bannerMapper.list()) {
            BannerListItemVO bannerListItemVO = new BannerListItemVO();
            bannerListItemVO.setId(banner.getId());
            bannerListItemVO.setUrl("http://localhost:8090/banner"+banner.getUrl());
            list.add(bannerListItemVO);
            log.debug(bannerListItemVO.getUrl());
        }
        return list;
    }
}
